# -*- coding: utf-8 -*-

from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
from django.forms.models import modelformset_factory

from django.shortcuts import render_to_response,render
from django.template import RequestContext

from django.http import HttpResponseRedirect, Http404
import math,logging
from django.views.decorators.cache import cache_page
import func

from forms import PurchaseReceiptForm as CurrentMainForm,PurchaseReceiptDetailForm as CurrentDetailItemForm
from models import  PurchaseReceipt as CurentDataModel,PurchaseReceiptDetail as CurentDataDetailModel

current_app = 'warehouse_re'
current_url = '/erp/re/'
title = '采购入库'

#@cache_page(60 * 1) 
@login_required()
def list(request,page=1):   
    #pr_choice = list(PR_STATUS_CHOICES)  
    #logging.error(pr_choice)
    
    return render_to_response("warehouse/common/list.html",
                              {'app': current_app,'current_url':current_url,
                               'title':title,'back_url':current_url,
                               }
                              ,context_instance=RequestContext(request))
@login_required()
def log(request,id):
    po = CurentDataModel.objects.get(pk=id)
    return render_to_response("warehouse/log.html",
                              {'app': current_app,'current_url':current_url,
                               'back_url':current_url+str(id),
                               'title':title,
                               'op_items':po.GetOperatorLog()
                               }
                              ,context_instance=RequestContext(request))
@login_required()
def detail(request,id):
    obj = CurentDataModel.objects.get(pk=id)
    obj.user = request.user
    form = None
    if request.method == 'POST':
        form = CurrentMainForm(request.POST,instance=obj) 
        if form.is_valid(): 
            form.save(True)
    else:        
        form = CurrentMainForm(instance=obj) 
        pass
    
    if obj.Can_Edit==False:
        #'PO_Title','PO_Supplier', 'PO_Employee_Audit','PO_Description','PO_ReceiptDateTime'
        for f in ['PR_Title','PR_Supplier', 'PR_ReceiptEmployee','PR_Description','PR_ReceiptDateTime']:
            form.fields[f].widget.attrs['readonly'] = True        
    
    return render_to_response("warehouse/common/detail.html",
                              {'title':title,'back_url':current_url,
                               'app': current_app,'current_url':current_url,
                               'form':form, 
                               'id':id, 
                               'obj':obj,
                               'current_url':current_url,
                               }
                              ,context_instance=RequestContext(request))

@login_required()
def do(request,id,do):
    o = CurentDataModel.objects.get(pk=id)
    o.user = request.user
    o.Do(request.user,do)
    return HttpResponseRedirect(current_url+id)

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.id and func.in_group(u,u'仓库'))
def add(request):
    if request.method == 'POST': # If the form has been submitted...
        form = CurrentMainForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            o_new = form.save(commit=False)             
            o_new.PR_CreateEmployee =  Employee.GetEmployeeFromUser(request.user) 
             
            o_new.save()
            return HttpResponseRedirect(current_url) # Redirect after POST
    else:
        form = CurrentMainForm() # An unbound form
        
    return render_to_response("warehouse/common/dialog.html",
                              {'app': current_app,'current_url':current_url,
                               'title':title,'back_url':current_url,
                               'form':form,
                               'post_url':current_url+'add',
                               'form_title':'新增收货单',
                               'form_help':''
                               }
                              ,context_instance=RequestContext(request))
    
    
@user_passes_test(lambda u: u.id and func.in_group(u,u'仓库'))
def item_del(request,id,item_id):
    o = CurentDataDetailModel.objects.get(id=item_id)
    o.delete()
    return HttpResponseRedirect(current_url+id)

@user_passes_test(lambda u: u.id and func.in_group(u,u'仓库'))
def item_add_edit(request,id,item_id=0):
    if request.method == 'POST': # If the form has been submitted...
        if (item_id==0):#add
            form = CurrentDetailItemForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass                 
                o_new = form.save(commit=False)
                o_new.PurchaseReceipt = PurchaseOrder.objects.get(pk=id)
                o_new.save()
    
                return HttpResponseRedirect(current_url+po_id) # Redirect after POST
        else: #edit
            poi = CurentDataDetailModel.objects.get(pk=item_id)
            form = CurrentDetailItemForm(request.POST,instance=poi) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass           
                form.save(commit=True)
                #pr_new = form.save(commit=False)
                #pr_new.PRI_PurchaseRequest = PurchaseRequest.objects.get(id=pr_id)             
                #pr_new.save()
    
                return HttpResponseRedirect(current_url+id) # Redirect after POST
    else:
        if (item_id==0):
            form = CurrentDetailItemForm() # An unbound form
        else:
            poi = CurentDataDetailModel.objects.get(id=item_id)
            form = CurrentDetailItemForm(instance=poi) # An unbound form
        
    return render_to_response("warehouse/common/dialog.html",
                              {'app': current_app,'current_url':current_url,
                               'title':title,'back_url':current_url+str(id),
                               'form':form,
                               'post_url':current_url+id+'/add',
                               'form_title':'新增收货条目',
                               'form_help':''
                                }
                              ,context_instance=RequestContext(request))
    
